﻿package com.thorqq.magictimer.action;

import com.thorqq.magictimer.R;
import com.thorqq.magictimer.core.ChildView;
import com.thorqq.magictimer.core.ChildViewParent;
import com.thorqq.magictimer.core.TAction;
import com.thorqq.magictimer.util.Util;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;

public class ActionVolumeChildView extends ChildView
{
    @SuppressWarnings("unused")
    private ChildViewParent mParent;
    private ActionVolume mAction;
    private Context mContext;
    private LayoutInflater mInflater;

    private AudioManager mAudioManager;
    private MediaPlayer mMediaPlayer;
    private Uri mUri;
    private Button mCurrentBtn;
    int mMaxVolRing;
    int mMaxVolNotification;
    
    int mOriginRingVolume;
    int mOriginNotificationVolume;

    private SeekBar mSbRing;
    private SeekBar mSbNotification;

    private Button mBtnRingVolumeTest;
    private Button mBtnNotificationVolumeTest;

    public ActionVolumeChildView(Context context, TAction action)
    {
        mContext = context;
        mAction = (ActionVolume) action;
    }

    @Override
    public void updateLayout()
    {
    }

    @Override
    protected void registerListener()
    {
        // 铃声滑动条
        mSbRing.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
        {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar)
            {
                mAction.setRingVolume(seekBar.getProgress());
                if(mMediaPlayer != null && mMediaPlayer.isPlaying())
                {
                    mAudioManager.setStreamVolume(AudioManager.STREAM_RING, seekBar.getProgress(), 0);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar arg0)
            {
            }

            @Override
            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2)
            {
            }
        });

        // 通知滑动条
        mSbNotification.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
        {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar)
            {
                mAction.setNotificationVolume(seekBar.getProgress());
                if(mMediaPlayer != null && mMediaPlayer.isPlaying())
                {
                    mAudioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, seekBar.getProgress(), 0);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar arg0)
            {
            }

            @Override
            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2)
            {
            }
        });

        mBtnRingVolumeTest.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                mCurrentBtn = mBtnRingVolumeTest;
                testVolume(Settings.System.DEFAULT_RINGTONE_URI, 
                        AudioManager.STREAM_RING, mSbRing.getProgress());
             }
        });

        mBtnNotificationVolumeTest.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                mCurrentBtn = mBtnNotificationVolumeTest;
                testVolume(Settings.System.DEFAULT_NOTIFICATION_URI, 
                        AudioManager.STREAM_NOTIFICATION, mSbNotification.getProgress());
            }
        });
    }
    
    private void registerMediaPlayerListener()
    {
        mMediaPlayer.setOnErrorListener(new OnErrorListener()
        {
            public boolean onError(MediaPlayer mp, int what, int extra)
            {
                restoreStreamVolume();
                mp.stop();
                mp.release();
                mMediaPlayer = null;
                switchPlayingBtnImage(mCurrentBtn, false);
                mUri = null;
                return true;
            }
        });
        
        mMediaPlayer.setOnCompletionListener(new OnCompletionListener()
        {
            @Override
            public void onCompletion(MediaPlayer mp)
            {
                restoreStreamVolume();
                switchPlayingBtnImage(mCurrentBtn, false);
                mUri = null;
            }
            
        });
    }
    
    private void switchPlayingBtnImage(Button btn, Boolean playing)
    {
        if(playing)
        {
            btn.setBackgroundResource(R.drawable.test_volume_playing);
        }
        else
        {
            btn.setBackgroundResource(R.drawable.test_volume);
        }
    }
    
    private void saveStreamVolume()
    {
        mOriginRingVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_RING);
        mOriginNotificationVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
    }
    
    private void restoreStreamVolume()
    {
        mAudioManager.setStreamVolume(AudioManager.STREAM_RING, mOriginRingVolume, 0);
        mAudioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, mOriginNotificationVolume, 0);
    }
    
    private void testVolume(Uri uri, int streamtype, int volume)
    {
        try
        {
            if(mMediaPlayer == null)
            {
                mMediaPlayer = new MediaPlayer();
                registerMediaPlayerListener();
            }

            if(mMediaPlayer.isPlaying())
            {
                restoreStreamVolume();
                mMediaPlayer.stop();
                switchPlayingBtnImage(mBtnNotificationVolumeTest, false);
                switchPlayingBtnImage(mBtnRingVolumeTest, false);
                if(uri.compareTo(mUri) == 0)
                {
                    return;
                }
            }
            mMediaPlayer.reset();

            //保存原来的音量
            saveStreamVolume();
            //临时设置为测试音量
            mAudioManager.setStreamVolume(streamtype, volume, 0);
            
            //播放音乐
            mMediaPlayer.setDataSource(mContext, uri);
            mMediaPlayer.setAudioStreamType(streamtype);
            mMediaPlayer.setLooping(false);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
            
            //
            switchPlayingBtnImage(mCurrentBtn, true);
            mUri = uri;
        } catch (Exception e)
        {
            restoreStreamVolume();
            switchPlayingBtnImage(mCurrentBtn, false);
            Toast.makeText(mContext, "播放音乐异常", Toast.LENGTH_SHORT).show();
            Util.log_ex(e);
        } 
    }

    @Override
    protected void doInitLayout(ChildViewParent parent)
    {
        Util.log("init ChildViewActionVolume");
        mInflater = LayoutInflater.from(mContext);
        mView = mInflater.inflate(R.layout.action_item_child_volume, null);
        mParent = parent;

        mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);

        mSbRing = (SeekBar) mView.findViewById(R.id.seekBarRingVolume);
        mSbNotification = (SeekBar) mView.findViewById(R.id.seekBarNotificationVolume);

        mMaxVolRing = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
        mMaxVolNotification = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);
        
        mSbRing.setMax(mMaxVolNotification);
        mSbNotification.setMax(mMaxVolNotification);

        mSbRing.setProgress(mAction.getRingVolume());
        mSbNotification.setProgress(mAction.getNotificationVolume());

        mBtnRingVolumeTest = (Button) mView.findViewById(R.id.btnRingVolumeTest);
        mBtnNotificationVolumeTest = (Button) mView.findViewById(R.id.btnNotificationVolumeTest);

    }

    @Override
    protected void doSetTag(Object object)
    {
        if (object instanceof ActionVolume)
        {
            mAction = (ActionVolume) object;
        }
    }

    @Override
    public void onClose()
    {
        if(mMediaPlayer != null && mMediaPlayer.isPlaying())
        {
            restoreStreamVolume();
            mMediaPlayer.stop();
            switchPlayingBtnImage(mBtnNotificationVolumeTest, false);
            switchPlayingBtnImage(mBtnRingVolumeTest, false);
            mUri = null;
        }

    }

}
